package com.freewater.javabase.demo.mutithread.multidigest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestThread extends Thread {

    private final String fileName;

    public DigestThread(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void run() {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            FileInputStream fileInputStream = new FileInputStream(this.fileName);
            DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, messageDigest);
            while (digestInputStream.read() != -1) ;
            digestInputStream.close();
            final byte[] digest = messageDigest.digest();
            BigInteger bigInteger = new BigInteger(digest).abs();
            final String hexDigest = bigInteger.toString(16).toUpperCase();
            System.out.println(Thread.currentThread().getName() + " hexDigest: " + hexDigest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
